<template>
  <div id="BacReqReception" style="height: 100%">
    <Breadcrumb content="标本接收/登记" />
    <div class="bodyContent">
      <div>
        <vxe-toolbar perfect>
          <template #buttons>
            <span class="margin-lr-xs">条码号:</span>
            <vxe-input placeholder="条码号" v-model="searchConditions.reqNo" @keydown="reqNoEnter" />
            <span class="margin-lr-xs">登记日期:</span>
            <vxe-input type="date" placeholder="登记日期" v-model="searchConditions.recepDate" @change="findList" />
            <span class="margin-lr-xs">检验目的:</span>
            <vxe-input placeholder="检验目的" v-model="searchConditions.reqPurposeId" />
            <span class="margin-lr-xs">标本号:</span>
            <vxe-input placeholder="标本号" v-model="searchConditions.sampleNo" />
          </template>
          <template #tools>
            <span class="margin-lr-xs">报告单元:</span>
            <SelectWorkGroup ref="SelectWorkGroupRef" :url="'/api/rptGroup/findRptGroupList'" :inputWidth="'100%'" :businessType="'20'" @getSelectedId="getSelectedId" />
          </template>
        </vxe-toolbar>
        <vxe-toolbar perfect>
          <template #buttons></template>
          <template #tools>
            <vxe-button type="text" class="button-blue" @click="findList" icon="vxe-icon-refresh" :loading="loading">查询</vxe-button>
            <vxe-button type="text" class="button-blue margin-left-xs" @click="print" :loading="loading">打印</vxe-button>
            <vxe-button type="text" class="button-blue margin-left-xs" @click="updateReqMain" :loading="loading">修改</vxe-button>
            <vxe-button type="text" class="button-blue margin-left-xs" :loading="loading">撤销登记</vxe-button>
            <vxe-button type="text" class="button-blue margin-left-xs" :loading="loading" @click="returnSpec">标本退回</vxe-button>
            <vxe-button type="text" class="button-blue margin-left-xs" @click="printLabel" :loading="loading">重打标签</vxe-button>
            <vxe-button type="text" class="button-blue margin-left-xs" @click="againReqNo" :loading="loading">重打条码</vxe-button>
            <vxe-button type="text" class="button-blue margin-left-xs" @click="insertReqMain" :loading="loading">录入</vxe-button>
            <vxe-button type="text" class="button-blue margin-left-xs" :loading="loading">发送双工</vxe-button>
            <vxe-button type="text" class="button-blue margin-left-xs" transfer placement="bottom">
              <template #default>流程单</template>
              <template #dropdowns>
                <vxe-button type="text" class="button-blue" content="预览流程单"></vxe-button>
                <vxe-button type="text" class="button-blue" content="打印流程单" status="danger"></vxe-button>
                <vxe-button type="text" class="button-blue" content="批量打印流程单"></vxe-button>
              </template>
            </vxe-button>
          </template>
        </vxe-toolbar>
      </div>
      <div class="area margin-top-xs">
        <Splitpanes class="splitpanes">
          <Pane size="60">
            <div class="tableBox">
              <vxe-table ref="tableRef" border="inner" align="left" class="mytable-scrollbar" :loading="loading" height="auto" :data="tableData" :row-config="{ isCurrent: true }" :column-config="{ resizable: true }" show-overflow keep-source :scroll-y="{ enabled: true }" @current-change="tableCellClick" :menu-config="menuConfig" @menu-click="contextMenuClickEvent">
                <!-- <vxe-column type="checkbox" width="26"></vxe-column> -->
                <vxe-column type="seq" title="#" width="30"></vxe-column>
                <vxe-column field="stateNa" title="状态" width="120"> </vxe-column>
                <vxe-column field="sampleTypeNa" title="标本类型" width="120"> </vxe-column>
                <vxe-column field="signTime" title="接收时间" width="90"> </vxe-column>
                <vxe-column field="patNa" title="姓名" width="150"> </vxe-column>
                <vxe-column field="reqPurpose" title="检验目的" width="150"> </vxe-column>
                <!-- <vxe-column field="reqNo" title="标本号" width="150"> </vxe-column> -->
                <vxe-column field="reqNo" title="条码号" width="150"> </vxe-column>
                <vxe-column field="isUrgent" title="加急" width="150">
                  <template #default="{ row }">
                    <el-tag type="success" v-if="row.isUrgent === '1' || row.isUrgent === 1">是</el-tag>
                    <el-tag type="danger" v-else>否</el-tag>
                  </template>
                </vxe-column>
                <vxe-column field="patTypeNa" title="病人类型" width="150"> </vxe-column>
                <vxe-column field="sexNa" title="性别" width="150"> </vxe-column>
                <vxe-column field="ageStr" title="年龄" width="150"> </vxe-column>
                <vxe-column field="reqDeptNa" title="申请科室" width="150"> </vxe-column>
                <vxe-column field="patNo" title="病历号" width="150"> </vxe-column>
                <vxe-column field="bedNo" title="床号" width="150"> </vxe-column>
                <vxe-column field="diagnose" title="临床诊断" width="150"> </vxe-column>
                <vxe-column field="reqDoctorNa" title="申请医生" width="150"> </vxe-column>
                <vxe-column field="samplingTime" title="采样时间" width="150"> </vxe-column>
                <vxe-column field="remark1" title="备注" width="150"> </vxe-column>
                <!-- <vxe-column field="remark1" title="标本备注" width="150"> </vxe-column> -->
                <vxe-column field="reqWard" title="病人病区" width="150"> </vxe-column>
              </vxe-table>
            </div>
          </Pane>
          <Pane size="40">
            <Splitpanes horizontal>
              <Pane size="30">
                <Cost ref="CostRef" />
              </Pane>
              <Pane size="70">
                <WkflwNodeCultu ref="WkflwNodeCultuRef" @changeSXWkflw="changeSXWkflw" @changeBXWkflw="changeBXWkflw" />
              </Pane>
            </Splitpanes>
          </Pane>
        </Splitpanes>
      </div>
    </div>
    <BacReqReceptionForm ref="BacReqReceptionFormModalRef" @confirmSave="saveReqMainEvent" @confirmSaveReset="confirmSaveReset" />
    <!-- 静默打印 -->
    <QuietPrint ref="quietPrint1Ref" :printParams="printParamsObj" />
    <!-- 标本退回 -->
    <vxe-modal v-model="returnReasonModule" width="40vw" height="30vw" show-footer destroy-on-close>
      <template #title>
        <span style="color: red">{{ title }}</span> </template>
      <template #default>
        <div>
          <!-- <vxe-textarea
              v-model="returnReason"
              placeholder="请输入回退理由"
              :style="{ height: 'calc(40vh - 20px) !important' }"
              resize="vertical"
              className="vxe-textarea-height"
            ></vxe-textarea> -->
          <UnqualifiedSpecRec ref="unqualifiedSpecRecRef" @chackedReasonChange="chackedReasonChange" />
        </div>
      </template>
      <template #footer>
        <div class="flex justify-end padding-right-xs">
          <vxe-button class-name="margin-left-sm" content="取消" @click="returnReasonModule = false"></vxe-button>
          <vxe-button class-name="margin-left-sm" status="primary" content="确定" @click="confirmReturnSpec"></vxe-button>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>

<script lang="ts" setup>
/**引入组件区 ==========*/
import Breadcrumb from '@/components/Breadcrumb.vue'; /**面包屑*/
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import XEClipboard from 'xe-clipboard';
import SelectWorkGroup from '@/views/lab_sys/lab_bus/components/SelectWorkGroup.vue'; //报告单元引入下拉组件
import Cost from './components/Cost.vue'; /**费用 */
import WkflwNodeCultu from './components/WkflwNodeCultu.vue';
import { formatDateTime, IsEmpty } from '@/utils/common';
import BacReqReceptionForm from './components/BacReqReceptionForm.vue'; /**手工录入、修改申请信息 */
import QuietPrint from '@/components/QuietPrint.vue'; /**静默打印组件 */
import UnqualifiedSpecRec from '@/components/UnqualifiedSpecRec.vue';

/**全局变量定义区 ==========*/
let { proxy }: any = getCurrentInstance();
/**左侧表格 */
const loading = ref(false); /**刷新+表格加载*/
const form = reactive({ keyvalue: '' }); /**根据关键字查询*/
const tableRef = ref<VxeTableInstance<RowVO>>(); /**表格ref标记*/
const tableData = reactive([]); /**表格数据*/
const SelectWorkGroupRef = ref(null); /**报告单元选择组件对象 */
const CostRef = ref(null); /**费用组件对象 */
const WkflwNodeCultuRef = ref(null); /**流程方案 节点 培养皿 */
const BacReqReceptionFormModalRef = ref(null); /**手工录入修改申请信息组件对象 */
const quietPrint1Ref = ref(null); /**静默打印组件对象 */

/**右侧表单*/
const BacReqReceptionFormRef = ref<InstanceType<typeof BacReqReceptionForm>>();
let currentRow: any = reactive({ id: '', code: '' });
let printParamsObj = ref(null); /**静默打印参数 */
let returnReasonModule = ref(false);
let searchConditions: any = reactive({
  rptGroupId: '' /**报告单元 */,
  reqNo: '' /**条码号 */,
  recepDate: formatDateTime(new Date(), 'yyyy-MM-dd') /**登记日期 */,
  reqPurposeId: '' /**检验目的 */,
  sampleNo: '' /**标本号 */
}); /**查询条件 */

let rptGroup = ref(''); /* 报告单元 */

let unqualifiedDetailIds = reactive({});
let title = ref('');

function chackedReasonChange(val: any) {
  unqualifiedDetailIds = val;
  // console.log('---------unqualifiedDetailIds-------:', unqualifiedDetailIds.value);
}

function returnSpec() {
  console.log(currentRow);
  if (IsEmpty(currentRow.reqNo) || IsEmpty(currentRow.id)) {
    //(this as any).$XModal.message({ content: '请先选择回退标本', status: 'warning' });
    VxeMessage('请先选择回退标本', VxeNotifyType.error);
    return;
  } else {
    title.value = '【患者姓名】 ' + currentRow.patNa + '  【检验目的】' + currentRow.testPurpose;
    returnReasonModule.value = true;
  }
}

function confirmReturnSpec() {
  if (unqualifiedDetailIds.length == 0 || IsEmpty(unqualifiedDetailIds)) {
    VxeMessage('请选择回退原因', VxeNotifyType.error);
    return;
  }
  loading.value = true;
  //当前登录用户 EmpId
  const url = '/lab/req/unqualified/detail/saveDetail';
  const data = {
    reqNo: currentRow.reqNo,
    unqualifiedDetailIds: unqualifiedDetailIds
  };
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res.status.code === 200) {
        VxeMessage('退回成功', VxeNotifyType.success);
        returnReasonModule.value = false;
        loading.value = false;
        findReqMainList();
        // const index = (proxy.$refs.specSignDetailTable as any).getRowIndex(currentSpecSignDetail);
        // specSignDetailList.splice(index, 1);
      } else {
        loading.value = false;
        VxeMessage('操作失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('操作失败', VxeNotifyType.error);
    });
}

/**vxe-table 表格右击属性*/
const menuConfig = reactive<VxeTablePropTypes.MenuConfig<RowVO>>({
  header: {
    options: [
      [
        { code: 'hideColumn', name: '隐藏列', disabled: false },
        { code: 'showAllColumn', name: '取消所有隐藏列', disabled: false }
      ]
    ]
  },
  body: {
    options: [
      [
        { code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', disabled: false },
        { code: 'reload', name: '刷新', disabled: false }
        //{ code: 'remove', name: '删除', disabled: false }
        // { code: 'save', name: '保存', prefixIcon: 'vxe-icon-save', disabled: false }
      ]
    ]
  },
  visibleMethod({ options, column }) {
    const isDisabled = !column;
    options.forEach((list) => {
      list.forEach((item) => {
        item.disabled = isDisabled;
      });
    });
    return true;
  }
});

/**方法定义区 =============*/
onMounted(() => {
  /**获取表格数据 */
  findList();
});

/**报告单元选中事件改变 */
function getSelectedId(e) {
  rptGroup.value = e.value;
}

/**获取 表格数据*/
const findList = () => {
  findReqMainList();
};

/**新增*/
async function addBacReqReception() {
  (proxy.$refs.tableRef as any).clearCurrentRow();
  BacReqReceptionFormRef.value?.addNew((e) => {
    //todo
  });
}

/**保存*/
function saveBacReqReception() {
  BacReqReceptionFormRef.value?.saveForm((e) => {
    // findList();
  });
}

/**删除*/
async function deleteBacReqReception(row) {
  proxy
    .$confirm('确定删除选中数据？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/lab/reqMain/deleteBacReqReception';
      proxy.$http
        .post(url, row)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('删除成功', VxeNotifyType.success);
            findList();
            BacReqReceptionFormRef.value?.clearFormData();
          } else {
            VxeMessage(res.status.msg, VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          // VxeMessage('删除异常', VxeNotifyType.error);
        });
    });
}

// 表格右击菜单项
const contextMenuClickEvent: VxeTableEvents.MenuClick<RowVO> = ({ menu, row, column }) => {
  const $table = tableRef.value;
  if ($table) {
    switch (menu.code) {
      case 'hideColumn':
        $table.hideColumn(column);
        break;
      case 'showAllColumn':
        $table.resetColumn(true);
        break;
      case 'copy':
        if (XEClipboard.copy((row as any)[column.field])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
        }
        break;
      case 'reload':
        findList();
        break;
      case 'insertAt':
        $table.insertAt({}, row || -1).then(({ row }) => {
          $table.setEditCell(row, column || 'name');
        });
        break;
      case 'remove':
        deleteBacReqReception(row);
        break;
      case 'save':
        //saveBacReqReception();
        break;
    }
  }
};

/**表格选中当前行*/
function tableCellClick({ row }) {
  Object.assign(currentRow, row);
  proxy.$forceUpdate();
  /**加载申请列表 */
  findReqMainDetailList(row);
  /**加载解决方案 */
  findBacWkflwList(row);
  /**加载培养基 */
  findBacCultureList(row);
}
/**加载申请列表 */
function findReqMainList(reqMainObj) {
  tableData.length = 0;
  const url = '/lab/reqMain/findLabReqMainListForBacReception';
  proxy.$http
    .get(url, { params: { recepDate: formatDateTime(searchConditions.recepDate, 'yyyy-MM-dd') } })
    .then((res: any) => {
      Object.assign(tableData, res.data);
      reqMainRowClick({ row: res.data[0] });
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
/**申请行选中事件 */
function reqMainRowClick({ row }) {
  Object.assign(currentRow, row);
  tableRef.value?.setCurrentRow(row);
  isOperation(row);
  findReqMainDetailList(row);
  findBacWkflwList(row);
  findBacCultureList(row);
}
/**是否能操作 */
function isOperation(reqMainObj) {
  if (reqMainObj && !IsEmpty(reqMainObj.mainInfoId)) {
    WkflwNodeCultuRef.value?.isOperation(true);
  } else {
    WkflwNodeCultuRef.value?.isOperation(false);
  }
}
/**加载申请项目 */
function findReqMainDetailList(reqMainObj) {
  CostRef.value?.getreqDetail(reqMainObj);
}
/**加载应用方案 */
function findBacWkflwList(reqMainObj) {
  if (!rptGroup.value) {
    setTimeout(() => {
      findBacWkflwList(reqMainObj);
    }, 100);
    return;
  }
  let reqMainEntry = {} as any;
  Object.assign(reqMainEntry, reqMainObj);
  reqMainEntry[`rptGroup`] = rptGroup.value;
  WkflwNodeCultuRef.value?.getreqDetail(reqMainEntry);
}
/**加载培养基 */
function findBacCultureList(reqMainObj) {
  WkflwNodeCultuRef.value?.getCultureDetail(reqMainObj);
}
/* 加载培养基，判断是否需要弹窗 */
async function findBacCultureListAsync(reqMainObj) {
  const res = await WkflwNodeCultuRef.value?.getCultureDetailAsync(reqMainObj);
}
/**条码号回车事件 */
function reqNoEnter(e) {
  if (e.$event.keyCode === 13) {
    proxy.$http
      .post(`/lab/reqMain/bacReqReception`, { reqNo: e.value, recepDate: formatDateTime(searchConditions.recepDate, 'yyyy-MM-dd 00:00:00') })
      .then((res: any) => {
        if (res && res.status && res.status.code === 1) {
          findReqMainList(res.data);
          /**加载申请列表 */
          findReqMainDetailList(res.data);
          /**加载解决方案 */
          findBacWkflwList(res.data);
          /**加载培养基 */
          findBacCultureListAsync(res.data);
          /**清空条码号 */
          searchConditions.reqNo = '';
        } else {
          const type = VXETable.modal.confirm(res.status.msg); /*不能改el  $confirm 回车事件冒泡你*/
          if (type === 'confirm') {
          }
          // VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage('新增药敏测试方法异常', VxeNotifyType.error);
      });
  }
}
/**手工录入申请信息 */
function insertReqMain() {
  BacReqReceptionFormModalRef.value?.showModal();
}

/**更新申请记录 */
function updateReqMain() {
  const row = tableRef.value?.getCurrentRecord();
  BacReqReceptionFormModalRef.value?.editShowModal(row);
}

/**保存微生物申请信息 */
function saveReqMainEvent(obj) {
  let url = `/lab/reqMain/${IsEmpty(obj.id) ? 'bacCreateReqMain' : 'bacUpdateReqMain'}`;
  proxy.$http
    .post(url, obj)
    .then((res: any) => {
      if (res && res.status && res.status.code !== 1) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      } else if (res && res.status && res.status.code === 1) {
        const row = tableRef.value?.getCurrentRecord();
        if (IsEmpty(obj.id)) {
          findList();
        } else {
          Object.assign(row, res.data);
        }
      } else {
        VxeMessage('请求错误', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('操作失败,请联系管理员', VxeNotifyType.error);
    });
}
/**更新申请、重新计算 申请项目、采用方案 培养基等 */
function confirmSaveReset(obj) {
  let url = `/lab/reqMain/bacUpdateReqMainWithReset`;
  proxy.$http
    .post(url, obj)
    .then((res: any) => {
      if (res && res.status && res.status.code !== 1) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      } else if (res && res.status && res.status.code === 1) {
        const row = tableRef.value?.getCurrentRecord();
        Object.assign(row, res.data);
        findList();
      } else {
        VxeMessage('请求错误', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('操作失败,请联系管理员', VxeNotifyType.error);
    });
}
/**切换首选方案 */
function changeSXWkflw(obj) {
  let url = `/lab/reqMain/changeDefaultWkflwForBacReception`;
  proxy.$http
    .post(url, obj)
    .then((res: any) => {
      if (res && res.status && res.status.code !== 1) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      } else if (res && res.status && res.status.code === 1) {
        const row = tableRef.value?.getCurrentRecord();
        Object.assign(row, res.data);
        findList();
      } else {
        VxeMessage('请求错误', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('操作失败,请联系管理员', VxeNotifyType.error);
    });
}
/**切换备选方案 */
function changeBXWkflw(obj) {
  let url = `/lab/reqMain/changeSecondWkflwForBacReception`;
  proxy.$http
    .post(url, obj)
    .then((res: any) => {
      if (res && res.status && res.status.code !== 1) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      } else if (res && res.status && res.status.code === 1) {
        const row = tableRef.value?.getCurrentRecord();
        Object.assign(row, res.data);
        findList();
        WkflwNodeCultuRef.value?.culutureScanBarCode();
      } else {
        VxeMessage('请求错误', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('操作失败,请联系管理员', VxeNotifyType.error);
    });
}
/**打印 */
function print() {
  const row = tableRef.value?.getCurrentRecord();
  if (!row || IsEmpty(row.reqNo)) {
    VxeMessage('请选择要打印的申请', VxeNotifyType.warning);
    return;
  }
  let url = `/api/pubReport/print`;
  proxy.$http
      .get(url)
      .then((res: any) => {
        if (res && res.status && res.status.code === 1) {
          printParamsObj.value = [{ ReportName: res.data.id, ReportParameters: [{ Name: 'code', Value: row.reqNo }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }];
        } else {
          VxeMessage('请求错误', VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage('操作失败,请联系管理员', VxeNotifyType.error);
      });
}
/**打印标签 */
function printLabel() {
  const row = tableRef.value?.getCurrentRecord();
  if (!row || IsEmpty(row.reqNo)) {
    VxeMessage('请选择要打印的申请', VxeNotifyType.warning);
    return;
  }
  let url = `/api/pubReport/againLable`;
  proxy.$http
      .get(url)
      .then((res: any) => {
        if (res && res.status && res.status.code === 1) {
          printParamsObj.value = [{ ReportName: res.data.id, ReportParameters: [{ Name: 'code', Value: row.reqNo }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }];
        } else {
          VxeMessage('请求错误', VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage('操作失败,请联系管理员', VxeNotifyType.error);
      });
}
/**打印标签 */
function againReqNo() {
  const row = tableRef.value?.getCurrentRecord();
  if (!row || IsEmpty(row.reqNo)) {
    VxeMessage('请选择要打印的申请', VxeNotifyType.warning);
    return;
  }
  let url = `/api/pubReport/againReqNo`;
  proxy.$http
      .get(url)
      .then((res: any) => {
       if (res && res.status && res.status.code === 1) {
         printParamsObj.value = [{ ReportName:res.data.id, ReportParameters: [{ Name: 'Id', Value: row.reqNo }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }];
       } else {
          VxeMessage('请求错误', VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage('操作失败,请联系管理员', VxeNotifyType.error);
      });
}
</script>
<style lang="scss" scoped>
#BacReqReception {
  height: calc(100%);

  .bodyContent {
    height: calc(100% - 60px);

    .area {
      background-color: $base-white;

      .splitpanes {
        height: calc(100vh - 180px);
        background-color: $base-white;

        .button-blue,
        .button-red {
          margin: 5px 0 5px 5px;
        }

        .tableBox {
          height: calc(100%);
        }
      }
    }
  }
}
</style>
